#!/bin/bash

# 定义要处理的文件和替换规则

# 处理application.yml文件
YML_FILE="/data/app/we-yan-agent/genie-backend/src/main/resources/application.yml"

# 替换后端端口
if grep -q 'port: 8080' "$YML_FILE"; then
    sed -i 's|port: 8080|port: 8082|g' "$YML_FILE"
    echo "$YML_FILE 中已替换 port: 8080"
else
    echo "$YML_FILE 中未找到 port: 8080，跳过替换"
fi

# 替换code_interpreter_url
if grep -q 'code_interpreter_url: http://127.0.0.1:1601' "$YML_FILE"; then
    sed -i 's|code_interpreter_url: http://127.0.0.1:1601|code_interpreter_url: http://172.21.240.6:8080/tool|g' "$YML_FILE"
    echo "$YML_FILE 中已替换 code_interpreter_url"
else
    echo "$YML_FILE 中未找到 code_interpreter_url 源值，跳过替换"
fi

# 替换deep_search_url
if grep -q 'deep_search_url: http://127.0.0.1:1601' "$YML_FILE"; then
    sed -i 's|deep_search_url: http://127.0.0.1:1601|deep_search_url: http://172.21.240.6:8080/tool|g' "$YML_FILE"
    echo "$YML_FILE 中已替换 deep_search_url"
else
    echo "$YML_FILE 中未找到 deep_search_url 源值，跳过替换"
fi

# 替换knowledge_search_url
if grep -q 'knowledge_search_url: http://127.0.0.1:1601' "$YML_FILE"; then
    sed -i 's|knowledge_search_url: http://127.0.0.1:1601|knowledge_search_url: http://172.21.240.6:8080/tool|g' "$YML_FILE"
    echo "$YML_FILE 中已替换 knowledge_search_url"
else
    echo "$YML_FILE 中未找到 knowledge_search_url 源值，跳过替换"
fi

# 替换mcp_client_url
if grep -q 'mcp_client_url: http://127.0.0.1:8188' "$YML_FILE"; then
    sed -i 's|mcp_client_url: http://127.0.0.1:8188|mcp_client_url: http://172.21.240.6:8080/mcp|g' "$YML_FILE"
    echo "$YML_FILE 中已替换 mcp_client_url"
else
    echo "$YML_FILE 中未找到 mcp_client_url 源值，跳过替换"
fi

# 替换auto_agent_url
if grep -q 'auto_agent_url: http://127.0.0.1:8080/AutoAgent' "$YML_FILE"; then
    sed -i 's|auto_agent_url: http://127.0.0.1:8080/AutoAgent|auto_agent_url: http://172.21.240.6:8080/backweb/AutoAgent|g' "$YML_FILE"
    echo "$YML_FILE 中已替换 auto_agent_url"
else
    echo "$YML_FILE 中未找到 auto_agent_url 源值，跳过替换"
fi

# 处理genie-tool/.env文件
TOOL_ENV_FILE="/data/app/we-yan-agent/genie-tool/.env"

# 替换FILE_SERVER_URL
if grep -q 'FILE_SERVER_URL=http://127.0.0.1:1601/v1/file_tool' "$TOOL_ENV_FILE"; then
    sed -i 's|FILE_SERVER_URL=http://127.0.0.1:1601/v1/file_tool|FILE_SERVER_URL=http://172.21.240.6:8080/tool/v1/file_tool|g' "$TOOL_ENV_FILE"
    echo "$TOOL_ENV_FILE 中已替换 FILE_SERVER_URL"
else
    echo "$TOOL_ENV_FILE 中未找到 FILE_SERVER_URL 源值，跳过替换"
fi

# 处理ui/.env文件
UI_ENV_FILE="/data/app/we-yan-agent/ui/.env"

# 替换SERVICE_BASE_URL
if grep -q 'SERVICE_BASE_URL="http://127.0.0.1:8080"' "$UI_ENV_FILE"; then
    sed -i 's|SERVICE_BASE_URL="http://127.0.0.1:8080"|SERVICE_BASE_URL=http://172.21.240.6:8080/backweb|g' "$UI_ENV_FILE"
    echo "$UI_ENV_FILE 中已替换 SERVICE_BASE_URL"
else
    echo "$UI_ENV_FILE 中未找到 SERVICE_BASE_URL 源值，跳过替换"
fi

echo "所有URL替换操作已完成"